<template>
    <div>
        <vxe-toolbar custom ref="toolbarRef">
            <template #buttons>
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="handleAdd"
                        v-if="this.editable && this.outType !== '销售出仓'"
                >
                    新 增
                </el-button>
            </template>
            <template #tools>

                <el-tooltip content="清空筛选" placement="top">
                    <vxe-button  icon="vxe-icon-delete" class="tool-btn" @click="$refs.tableRef.clearFilter()" circle></vxe-button>
                </el-tooltip>

                <vxe-button icon="vxe-icon-refresh" class="tool-btn" @click="refresh" circle
                            style="margin-right: 12px;"></vxe-button>
            </template>
        </vxe-toolbar>
        <vxe-grid
                v-bind="gridOptions"
                ref="tableRef"
                show-footer
                class="mytable-scrollbar"
                :data="list"
                :edit-rules="validRules"
                :tooltip-config="{ zIndex: 9999 }"
                :customConfig="customConfig"
                :menu-config="menuConfig"
                :footer-method="footerMethod"
                :edit-config="{
                trigger: 'click',
                mode: 'row',
                showUpdateStatus: true,
                showInsertStatus: true,
                beforeEditMethod:beforeEdit}"
                @edit-closed="editClosedEvent"
                @edit-actived="editActivedEvent"
                @menu-click="contextMenuClickEvent">

            <template #aboutNo_header>
                {{tableHeader.aboutNoHeader}}
            </template>
            <template #aboutItem_header>
                {{tableHeader.aboutItemHeader}}
            </template>

            <template #num_edit="scope">
                <vxe-input v-model="scope.row.num" type="integer" max="99999999" min="0" :controls="false" :disabled="this.logisticsNo !== ''"
                           @blur="(value)=>checkNum(scope.row.num, scope.row)"
                           @change="(value)=>calTotalPrice(scope.row.price,value.value,scope)"
                ></vxe-input>
            </template>

            <template #stockId_edit="scope">
                <el-select v-model="scope.row.stockId"
                           :filterable="true"
                           :clearable="false"
                           placeholder="请选择仓位"
                           @change="handleSelectStockName(scope.row.stockId,scope.row)"
                           :disabled="isEditStock"
                           @blur="(value)=>checkNum(scope.row.num, scope.row)"
                           type="string" transfer>
                    <el-option
                            v-for="item in stockNameDic"
                            :key="item.id"
                            :value="item.id"
                            :label="item.stockName"/>
                </el-select>
                <!--<span v-else>{{scope.row.stockName}}</span>-->
            </template>

            <template #stockId_default="scope">
                <span>{{formatStockName(scope.row)}}</span>
            </template>

            <template #stockArea_edit="scope">
                <vxe-input v-model="scope.row.stockArea"></vxe-input>
            </template>
            <template #packSpec_edit="scope">
                <vxe-input v-model="scope.row.packSpec" ></vxe-input>
            </template>
            <template #packCtnNum_edit="scope">
                <vxe-input v-model="scope.row.packCtnNum" type="integer" max="99999999" min="0" :controls="false"
                ></vxe-input>
                <!--@blur="(value)=>checkNum(scope.row.num, scope.row)"-->
                <!--@change="(value)=>calTotalNum(scope.row.price,value.value,scope)"-->

            </template>
<!--            <template #packUnit_edit="scope">-->
<!--                <el-select v-model="scope.row.packUnit"-->
<!--                           :clearable="true"-->
<!--                           :filterable="true"-->
<!--                           placeholder="请选择包装单位"-->

<!--                           type="string" transfer>-->
<!--                    &lt;!&ndash;          @change="handleSelectPackUnit"&ndash;&gt;-->
<!--                    <el-option-->
<!--                            v-for="item in packUnitDic"-->
<!--                            :key="item.name"-->
<!--                            :value="item.name"-->
<!--                            :label="item.name+' - '+item.type"/>-->
<!--                </el-select>-->
<!--            </template>-->

          <template #qcNo_edit="scope">
            <vxe-input v-model="scope.row.qcNo" :controls="false"></vxe-input>
          </template>

            <template #remark_edit="scope">
                <vxe-input v-model="scope.row.remark" ></vxe-input>
            </template>
<!--            <template #price_edit="scope">-->
<!--                <vxe-input v-model="scope.row.price" type="float" digits="5"  max="99999999" :controls="false"  @change="(value)=>calTotalPrice(value.value,scope.row.num,scope)"-->
<!--                ></vxe-input>-->
<!--            </template>-->

            <template #btn_default="{ row }">
                <template v-if="!isActiveStatus(row) && this.editable">
                    <!--<el-tooltip content="修改" placement="top">-->
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--type="primary"-->
                    <!--@click="handleUpdate(row)"-->
                    <!--&gt;修改-->
                    <!--</el-button>-->
                    <!--</el-tooltip>-->
                  <el-tooltip content="查看QC信息" placement="top">
                    <el-button
                        icon="el-icon-view"
                        link
                        size="small"
                        type="primary"
                        @click="handleOpenQC(row)"
                    ></el-button>
                  </el-tooltip>
                    <el-tooltip content="删除" placement="top" v-if="row.isGen!==1">
                        <el-button
                                icon="el-icon-delete"
                                link
                                size="small"
                                type="primary"
                                @click="handleDelete(row)"
                        ></el-button>
                    </el-tooltip>
                </template>
                <template v-else>
                </template>
            </template>
        </vxe-grid>
        <select-stock-summary ref="selectStockSummary" @setStockSummaryList="setStockSummaryList"></select-stock-summary>
        <select-prod-item ref="selectProdItemRef" @setProdItemList="setProdItemList"></select-prod-item>
        <select-order-item ref="selectOrderItemRef" @setOrderItemList="setOrderItemList"></select-order-item>
        <select-purchase-item ref="selectPurchaseItemRef" @setPurchaseItemList="setPurchaseItemList"></select-purchase-item>
        <select-prod-summary ref="selectProdSummaryRef" @setProdSummary="setProdSummary" ></select-prod-summary>
    </div>
</template>

<script>
    import {findList,overflowNum} from "@/api/anwise/stock/stock_out_item";
    import {checkSelectStock} from "@/api/anwise/stock/stock_out_main";
    import {mapGetters} from "vuex";
    import {select as unitSelect} from "@/api/anwise/unit_info";
    import {select as supplierSelect} from "@/api/anwise/supplier";
    import selectStockSummary from './select_stock_summary.vue';
    import selectMaterial from './select_material.vue';
    import selectProdItem from './select_prod_item.vue';
    import {markRaw} from "vue";
    import {stockHomeSelect,selectStockHomeDict} from "@/api/anwise/stock_home"
    import SelectOrderItem from "./select_order_item.vue";
    import selectPurchaseItem from './select_purchase_item.vue';
    import selectProdSummary from './select_prod_summary.vue';
    import {generateQCSign} from "@/api/common";


    export default {
        components: {
            selectStockSummary,
            selectMaterial,
            selectProdItem,
            SelectOrderItem,
            selectPurchaseItem,
            selectProdSummary
        },
        props: {
            // 出仓类型
            outType: {
                type: String,
                default: "",
            },
            fromDept: {
                type: String,
                default: "",
            },
            toNo:{
                type: String,
                default: "",
            },
            toName:{
              type:String,
              default:"",
            },
            isRole:{
                type: String,
                default:"",
            },
            toDept:{
                type: String,
                default:"",
            },
            bankId:{
                type:String,
                default:"",
            },
            logisticsNo:{
                type:String,
                default:"",
            }
        },
        data() {
            return {
                idNo: '',
                dateFormat: 'YYYY-MM-DD',
                pickerOptions: {},
                editRow: {},
                rowIndex: '',
                box: false,
                isEdit: false,
                iconSearch: true,
                searchShow: false,
                editable: true,
                list: [],
                stockNameDic:[],
                customConfig: {
                    storage: true,
                    checkMethod({column}) {
                        if (['facName'].includes(column.field)) {
                            return false
                        }
                        return true
                    },
                },
                menuConfig: {},
                form: {},
                query: {},
                loading: true,
                data: [],
                selectionList: [],
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                subVisible: false,
                direction: 'rtl',
                customerName: "安伟客户表",
                customerTypeList: [],
                tableHeader: {
                    aboutNoHeader: "",
                    aboutItemHeader: "",
                },
                packUnitDic: [],
                nameOptions: [{data: null}],
                validRules: {
                    price: [
                        {required: true, message: '单价必须填写'}
                    ],
                    num: [
                        {required: true, message: '数量必须填写'}
                    ],
                    stockId: [
                        {required: true, message: '仓位必须填写'}
                    ],
                },
                gridOptions: {
                    height: '400px',
                    border: true,
                    showOverflow: true,
                    keepSource: true,
                    size: "medium",
                    rowConfig: {
                        // keyField: 'id',
                        isHover: true
                    },
                    columnConfig: {
                        resizable: true
                    },
                    // editRules: ,
                    columns: [
                        // {type: 'checkbox', width: 50, fixed:'left', visible: true},
                        // {type: 'seq', width: 50, fixed:'left', align: "center"},
                        {
                            title: "出仓单号",
                            field: "idNo",
                            minWidth: 120,
                        },
                        {
                            title: "出仓项",
                            field: "itemNo",
                            minWidth: 120,
                        },
                        {
                            title: "相关单号",
                            field: "aboutNo",
                            minWidth: 120,
                            slots: {header: 'aboutNo_header'},
                        },
                        {
                            title: "相关项",
                            field: "aboutItem",
                            minWidth: 120,
                            slots: {header: 'aboutItem_header'},
                        },
                        {
                            title: "订单编号",
                            field: "orderNo",
                            minWidth: 120,
                        },
                        {
                            title: "物料编号",
                            field: "materialNo",
                            minWidth: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "客户条码",
                            field: "barCode",
                            minWidth: 120,
                        },
                        {
                            title: "物料名称",
                            field: "materialName",
                            minWidth: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "规格",
                            field: "specification",
                            minWidth: 120,
                        },
                        {
                            title: "单位",
                            field: "unit",
                            minWidth: 120,
                        },
                        {
                            title: "数量",
                            field: "num",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'num_edit'}
                        },
                        // {
                        //     title: "单价",
                        //     field: "price",
                        //     minWidth: 120,
                        //     editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                        //     slots: {edit: 'price_edit'}
                        // },
                        // {
                        //     title: "金额",
                        //     field: "totalPrice",
                        //     minWidth: 120,
                        // },
                        {
                            title: "包装规格",
                            field: "packSpec",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'packSpec_edit'}
                        },
                        {
                            title: "包装箱数",
                            field: "packCtnNum",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'packCtnNum_edit'}
                        },
                        {
                            title: "仓位",
                            field: "stockId",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'stockId_edit',default: 'stockId_default'}
                        },
                        {
                            title: "交货地点",
                            field: "deliAddr",
                            width: 200,
                        },
                        {
                            title: "备注",
                            field: "remark",
                            minWidth: 230,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'remark_edit'}
                        },
                        {
                            title: "箱唛",
                            field: "packLabel",
                            minWidth: 230,
                        },
                        {
                            title: "箱唛颜色",
                            field: "labelColor",
                            minWidth: 120,
                        },
                      {
                        title: "QC编号",
                        field: "qcNo",
                        minWidth: 120,
                        editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                        slots: {edit: 'qcNo_edit'}
                      },
                        {
                            field: 'btn',
                            title: '操作',
                            minWidth: 120,
                            align: "center",
                            fixed: "right",
                            visible: true,
                            slots: {default: 'btn_default'}
                        }
                    ]
                },
                supplierDic: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.stock_in_item_add, false),
                    viewBtn: this.validData(this.permission.stock_in_item_view, false),
                    delBtn: this.validData(this.permission.stock_in_item_delete, false),
                    editBtn: this.validData(this.permission.stock_in_item_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            },
            isEditStock(){
                return this.outType === "其它出仓" || this.outType === "工程领料" || this.outType === "盘亏出仓" ||
                this.outType === "品质领料" || this.outType === "样办出仓" || this.outType === "报废出仓";
            }
        },
        watch: {
            'outType'() {
                this.changeByOutType();
            },
            'toNo'(){
                this.changeByToNo();
            }
        },
        mounted() {
            this.isEdit = false;
            this.disabledCommit(false);
            this.init();
            this.$nextTick(() => {
                this.$refs.tableRef.connect(this.$refs.toolbarRef);
            })
        },
        methods: {
          handleOpenQC(row) {
            if (row.qcNo) {
              generateQCSign().then(res => {
                console.log("res", res);
                if (res.data.success) {
                  if (this.inType === "生产出仓") {
                    window.open("https://www.agop.com.cn/pc/views/qc/final_inspection/final_inspection_show.html?INSP_NO=" + row.qcNo + "&sign=" + res.data.data.sign + "&timestamp=" + res.data.data.timestamp);
                  } else {
                    window.open("https://www.agop.com.cn/pc/views/qc/material_inspection/material_inspection_show.html?INSP_NO=" + row.qcNo + "&sign=" + res.data.data.sign + "&timestamp=" + res.data.data.timestamp);
                  }
                }
              })
            } else {
              this.$message({
                type: "error",
                message: "请填写QC编号!"
              });
            }

          },
            init() {
                supplierSelect().then(res => {
                    this.supplierDic = res.data.data;
                })
                unitSelect().then(res => {
                    this.packUnitDic = res.data.data;
                })

                this.changeByOutType();
            },
            checkNum(num, row) {
                row.outType = this.outType;
                row.totalPrice = '';
                overflowNum(row).then(res => {
                    if (parseInt(num) > parseInt(res.data.data)) {
                        row.num = res.data.data;
                        if(row.maxNum && row.maxNum > 0 && row.num && row.num > 0){
                            row.packCtnNum =Math.floor(row.num/row.maxNum)
                            row.packSpec = row.maxNum+"*"+row.packCtnNum;
                            let i = row.num%row.maxNum;
                            if(i> 0){
                                if(row.packCtnNum < 1) {
                                    row.packSpec = i + "*1";
                                } else {
                                    row.packSpec = row.maxNum+"*"+row.packCtnNum+ " + " + i + "*1";
                                }
                                row.packCtnNum = parseInt(row.packCtnNum)+1;
                            }
                        }else {
                            row.packSpec = "";
                            row.packCtnNum = "";
                        }
                        if (row.price && row.num) {
                            row.totalPrice = row.price * row.num;
                        }
                        this.updateFooterEvent();
                        if(row.outType === "退货出仓" || row.outType === "退料出仓"){
                            this.$message({
                                type: "warning",
                                message: "因可退数量或仓存数量限制，数量不能大于["+row.num+"]!"
                            });
                        }else if(row.outType === "生产出仓"){
                            this.$message({
                                type: "warning",
                                message: "因可出数量或仓存数量限制，数量不能大于["+row.num+"]!"
                            });
                        }else if(row.outType === "领料出仓"){
                            this.$message({
                                type: "warning",
                                message: "因可领数量或仓存数量限制，数量不能大于["+row.num+"]!"
                            });
                        }
                    }
                })
            },
            formatStockName(row){
                let value = "";
                this.stockNameDic.forEach(res => {
                    if (res.id === row.stockId) {
                        value = res.stockName
                        row.stockName = res.stockName;
                    }
                })
                return value;
            },
            handleSelectStockName(value,row){
                if (row.outType !== '销售出仓') {
                    row.fromDept = this.fromDept;
                    row.totalPrice = '';
                    checkSelectStock(row).then(res => {
                        if (!res.data.success) {
                            row.stockId = "";
                        }
                    }, error => {
                        row.stockId = "";
                    })
                }
            },
            handleSelectPackUnit(value) {
                console.log(value)
            },
            changeByToNo(){
                const $table = this.$refs.tableRef;
                if($table.getTableData().fullData.length>0){
                    this.$message({
                        type: "warning",
                        message: "切换出仓类型或重新选择供应商会自动清空出仓项！"
                    });
                    $table.loadData([]);
                }
            },
            changeByOutType() {
                const $table = this.$refs.tableRef;
                this.stockNameDic = [];
                $table.showColumn("aboutNo");
                $table.showColumn("aboutItem");
                $table.hideColumn("orderNo");
                $table.hideColumn("deliAddr");
                $table.hideColumn("qcNo");
                let stockHomeType=this.outType;
                if (this.outType === "销售出仓") {
                    if(this.isRole === 1){
                        this.tableHeader.aboutNoHeader = "订单编号";
                        this.tableHeader.aboutItemHeader = "订货项";
                    }
                    $table.columns[10].editRender.enabled = false;
                }else if(this.outType === "生产出仓"){
                    if(this.isRole === 3){
                        this.tableHeader.aboutNoHeader = "生产编号";
                        this.tableHeader.aboutItemHeader = "生产项";
                    }
                    $table.showColumn("orderNo");
                    $table.showColumn("deliAddr");
                    $table.showColumn("qcNo");
                    $table.columns[10].editRender.enabled = true;
                } else if (this.outType === "领料出仓") {
                    this.tableHeader.aboutNoHeader = "生产编号";
                    $table.hideColumn("aboutItem");
                    $table.columns[10].editRender.enabled = true;
                } else if (this.outType === "退货出仓") {
                    this.tableHeader.aboutNoHeader = "生产编号";
                    this.tableHeader.aboutItemHeader = "生产项";
                    $table.showColumn("orderNo");
                    $table.columns[10].editRender.enabled = true;
                } else if (this.outType === "退料出仓") {
                    this.tableHeader.aboutNoHeader = "采购单号";
                    this.tableHeader.aboutItemHeader = "采购项";
                    $table.columns[10].editRender.enabled = true;
                } else if (this.outType === "其它出仓" || this.outType === "工程领料" || this.outType === "盘亏出仓" ||
                    this.outType === "品质领料" || this.outType === "样办出仓" || this.outType === "报废出仓"||this.outType === "调拨出仓") {
                    this.tableHeader.aboutNoHeader = "相关单号";
                    this.tableHeader.aboutItemHeader = "相关项";
                    $table.hideColumn("aboutNo");
                    $table.hideColumn("aboutItem");
                    $table.columns[10].editRender.enabled = true;
                }
                if(this.isEditStock){//仓位下拉选择禁用时查询全部仓位
                    selectStockHomeDict().then(res=>{
                        this.stockNameDic = res.data.data;
                    })
                }else{//选择仓位时查询当前机构关联仓位
                    stockHomeSelect(stockHomeType).then(res=>{
                        this.stockNameDic = res.data.data;
                    })
                }
                this.$emit("disabledFiled", false);
                $table.loadData([]);
            },
            setData(editable, idNo) {
                if (idNo) {
                    this.query.idNo = idNo
                    this.idNo = idNo
                }
                this.changeByOutType();
                this.onLoad(this.page)
                this.editable = editable;
            },
            updateStatus(scope) {
                this.$refs.tableRef.updateStatus(scope);
            },
            calcSum(list, field) {
                let count = 0
                list.forEach(item => {
                    count += Number(item[field])
                })
                if (field == 'totalPrice') {
                    return this.$toFixed(count,2);
                } else {
                    return this.$toFixed(count,0);
                }
            },
            // 在值发生改变时更新表尾合计
            updateFooterEvent(params) {
                let xTable = this.$refs.tableRef
                xTable.updateFooter()
            },
            footerMethod(table) {
                console.log("table", table);
                return [
                    table.columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计'
                        }
                        if (['num', 'totalPrice','packCtnNum'].includes(column.field)) {
                            return this.calcSum(table.data, column.field)
                        }
                        return null
                    })
                ]
            },
            calTotalPrice(price, num, scope) {
                console.log("price", price);
                console.log("num", num);
                this.$refs.tableRef.updateStatus(scope);
                let row = scope.row;
                console.log(row)
                console.log("row.maxNum",row.maxNum)
                if(row.maxNum && row.maxNum > 0 && row.num && row.num > 0){
                    row.packCtnNum =Math.floor(num/row.maxNum)
                    row.packSpec = row.maxNum+"*"+row.packCtnNum;
                    let i = num%row.maxNum;
                    if(i> 0){
                        if(row.packCtnNum < 1) {
                            row.packSpec = i + "*1";
                        } else {
                            row.packSpec = row.maxNum+"*"+row.packCtnNum+ " + " + i + "*1";
                        }
                        row.packCtnNum = parseInt(row.packCtnNum)+1;
                    }
                }else {
                    row.packSpec = "";
                    row.packCtnNum = "";
                }
                if (price && num) {
                    row.totalPrice = this.$toFixed(price * num,2);
                }
            },
            calTotalNum(price,packCtnNum, scope) {
                console.log("price", price);
                this.$refs.tableRef.updateStatus(scope);
                let row = scope.row;
                if(row.maxNum && packCtnNum && row.num){
                    row.num = packCtnNum*row.maxNum;
                    row.packSpec = row.maxNum+"*"+packCtnNum;
                }
                if (price && row.num) {
                    row.totalPrice = price * row.num;
                }
            },
            refresh() {
                this.page = {
                    pageSize: 10,
                    currentPage: 1,
                }
                this.query = {}
                this.onLoad(this.page)
            },
            pageChange(e) {
                this.page = {
                    pageSize: e.pageSize,
                    currentPage: e.currentPage,
                }
                this.onLoad(this.page)
            },

            isActiveStatus(row) {
                const $table = this.$refs.tableRef
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            clearAll() {
                this.data = [];
                this.$refs.tableRef.remove();
            },
            async setStockSummaryList(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => val.stockSummaryId === item.summaryId)) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                stockSummaryId: item.summaryId,
                                barCode: item.barCode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: 0,
                                packUnit: item.packUnit,
                                maxNum: item.maxNum,
                                packNum: item.packNum,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                stockId: item.stockId,
                                stockName: item.stockName,
                                stockArea: item.stockArea,
                                outType: $this.outType,
                                // qcNo: item.qcNo,
                                // $cellEdit: true
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                mat.totalPrice = mat.num * mat.price;
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setProdItemList(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                console.log(selectData)
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => val.aboutNo === item.tabNo && val.aboutItem === item.tabItem)) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                stockSummaryId: item.summaryId,
                                aboutNo: item.tabNo,
                                aboutItem: item.tabItem,
                                barCode: item.barcode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: item.price,
                                // packUnit: item.packUnit,
                                maxNum: item.maxNum,
                                packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                outType: $this.outType,
                                orderNo: item.orderNo,
                                deliAddr: item.deliAddr,
                                // $cellEdit: true
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                mat.totalPrice = mat.num * mat.price;
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setOrderItemList(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                console.log(selectData)
                const existsList = this.$refs.tableRef.getTableData().fullData;
                let $this = this;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => val.aboutNo === item.idNo && val.aboutItem === item.itemNo)) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                // stockSummaryId:item.summaryId,
                                aboutNo: item.idNo,
                                aboutItem: item.itemNo,
                                barCode: item.barCode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: item.price,
                                // packUnit: item.packUnit,
                                maxNum: item.maxNum,
                                packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                outType: $this.outType,
                                // $cellEdit: true
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                mat.totalPrice = mat.num * mat.price;
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setPurchaseItemList(list){
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                console.log(selectData)
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => val.aboutNo === item.idNo && val.aboutItem === item.itemNo)) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                stockSummaryId: item.summaryId,
                                aboutNo: item.idNo,
                                aboutItem: item.itemNo,
                                barCode: item.barCode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: item.price,
                                // packUnit: item.packUnit,
                                packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                maxNum: item.maxNum,
                                outType: $this.outType,
                                // $cellEdit: true
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                mat.totalPrice = mat.num * mat.price;
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            async setProdSummary(list){
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                console.log(selectData)
                let $this = this;
                const existsList = this.$refs.tableRef.getTableData().fullData;
                if (!$table.getEditRecord()) {
                    for (let i = 0; i<selectData.length; i++) {
                        let item = selectData[i];
                        if (!existsList.some((val) => val.aboutNo === item.tabNo && val.materialNo === item.materialNo)) {
                            let maxNo = 0;
                            if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                                maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].itemNo);
                            }
                            let mat = {
                                // id: '',
                                itemNo: maxNo + 1,
                                // stockSummaryId:item.summaryId,
                                aboutNo: item.tabNo,
                                // aboutItem: item.itemNo,
                                barCode: item.barcode,
                                materialNo: item.materialNo,
                                materialName: item.materialName,
                                specification: item.specification,
                                unit: item.unit,
                                price: 0,
                                outType: $this.outType,
                                maxNum: item.maxNum,
                                // packUnit: item.packUnit,
                                // packNum: item.packSize,
                                packLabel: item.packLabel,
                                labelColor: item.labelColor,
                                // $cellEdit: true
                            }
                            await overflowNum(mat).then(res => {
                                mat.num = Number(res.data.data).toFixed(0);
                                if(mat.maxNum && mat.maxNum >0) {
                                    mat.packCtnNum = Math.floor(mat.num / mat.maxNum)
                                    mat.packSpec = mat.maxNum + "*" + Math.floor(mat.num / mat.maxNum);
                                    let i = Math.floor(mat.num%mat.maxNum);
                                    if(i> 0){
                                        if(mat.packCtnNum < 1) {
                                            mat.packSpec = i + "*1";
                                        } else {
                                            mat.packSpec = mat.maxNum+"*"+mat.packCtnNum+ " + " + i + "*1";
                                        }
                                        mat.packCtnNum = parseInt(mat.packCtnNum)+1;
                                    }
                                }
                                mat.totalPrice = mat.num * mat.price;
                                $this.$refs.tableRef.insertAt(mat, -1);
                            })
                        }
                    }
                }
            },
            handleAdd() {
                if (!this.outType) {
                    this.$message({
                        type: "error",
                        message: "请先选择出仓类型!"
                    });
                    return;
                }
                if (this.outType === "销售出仓") {
                    if(this.isRole === 1){
                        if (!this.toDept || !this.toNo || !this.toName) {
                            this.$message({
                                type: "error",
                                message: "请先选择客户信息!"
                            });
                            return;
                        }
                        if(!this.bankId){
                            this.$message({
                                type: "error",
                                message: "请先选择收款方!"
                            });
                            return;
                        }
                        this.$refs.selectOrderItemRef.showSelect('stockOut',this.$refs.tableRef.getTableData().fullData, this.toNo,this.bankId);
                    }
                }else if(this.outType === "生产出仓"){
                    this.$refs.selectProdItemRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.fromDept,1);
                } else if (this.outType === "领料出仓") {
                    if (!this.toDept || !this.toNo || !this.toName) {
                        this.$message({
                            type: "error",
                            message: "请先选择加工商!"
                        });
                        return;
                    }
                    this.$refs.selectProdSummaryRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.toDept);
                } else if (this.outType === "退货出仓") {
                    if (!this.toDept || !this.toNo || !this.toName) {
                        this.$message({
                            type: "error",
                            message: "请先选择加工商!"
                        });
                        return;
                    }
                    this.$refs.selectProdItemRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.toDept,2);
                } else if (this.outType === "退料出仓") {
                    if (!this.toDept || !this.toNo || !this.toName) {
                        this.$message({
                            type: "error",
                            message: "请先选择采购商!"
                        });
                        return;
                    }
                    this.$refs.selectPurchaseItemRef.showSelect(this.$refs.tableRef.getTableData().fullData, this.toDept,2);
                } else if(this.outType === "其它出仓" || this.outType === "工程领料" || this.outType === "盘亏出仓" ||
                    this.outType === "品质领料" || this.outType === "样办出仓" || this.outType === "报废出仓"){
                    this.$refs.selectStockSummary.showSelect(this.$refs.tableRef.getTableData().fullData);
                }
            },
            contextMenuClickEvent(data) {
                const menu = data.menu;
                const row = data.row;
                const column = data.column;
                const $table = this.$refs.tableRef
                if ($table) {
                    switch (menu.code) {
                        case 'hideColumn':
                            $table.hideColumn(column)
                            break
                        case 'showAllColumn':
                            $table.resetColumn(true)
                            break
                        case 'copy':
                            // if (XEClipboard.copy(row[column.field])) {
                            //   ElMessage.success('保存成功')
                            // }
                            // ElMessage.success('复制成功')
                            break
                        case 'reload':
                            //  findList()
                            break
                        case 'insertAt':
                            $table.insertAt({}, row || -1).then(({row}) => {
                                $table.setEditCell(row, column || 'name')
                            })
                            break
                        case 'remove':
                            $table.remove(row)
                            break
                        case 'save':
                            // ElMessage.success('保存成功')
                            break
                    }
                }
            },
            disabledCommit(data) {
                this.$emit("disabledCommit", data);
            },
            editActivedEvent(row) {//激活单元格事件
                this.isEdit = true;
                this.disabledCommit(true);
            },
            editClosedEvent(row) {
                console.log(row)
                const $table = this.$refs.tableRef;
                $table.clearValidate();
                this.disabledCommit(false);
            },
            async handleSaveRow(row) {
                const err = await this.validEvent(row);
                if (err) {
                    return
                }

            },
            async validEvent(row) {
                const $table = this.$refs.tableRef
                const errMap = await $table.validate(row).catch(errMap => errMap)
                return errMap;

            },
            formatType(value) {
                let value2 = "";
                this.customerTypeList.forEach(res => {
                    if (value === res.dictKey) {
                        value2 = res.dictValue;
                    }
                });
                return value2
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            async handleDelete(row) {
                const $table = this.$refs.tableRef
                if (row.id) {
                    this.$confirm('是否确认删除?', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        if ($table.getTableData().fullData.length === 1) {
                            this.$emit("disabledFiled", false);
                        }
                        $table.remove(row)
                    }).then(() => {
                        this.$message({type: "success", message: "操作成功，保存后生效!"});
                    })
                } else {
                    if ($table.getTableData().fullData.length === 1) {
                        this.$emit("disabledFiled", false);
                    }
                    $table.remove(row)
                }
            },
            beforeEdit({row, rowIndex, column, columnIndex}) {
                return this.editable;
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                if (this.$refs.crud) this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            formateDate(list) {
                list.forEach(item => {
                    item.totalPrice = this.$toFixed(item.num * item.price,3);
                    // let scope = {row:item}
                    // this.calTotalPrice(item.price,item.num,scope)
                })
                this.$nextTick(() => {
                    this.$refs.tableRef.getTableData().fullData.forEach(item=>{
                        if (item.isGen===1 && !item.stockId) {
                            item.stockId=' ';
                        }
                    })
                });
            },
            onLoad(page, params = {}) {
                this.query.idNo = this.idNo;
                if (this.$refs.tableRef.getInsertRecords().length > 0 || this.$refs.tableRef.getRemoveRecords().length > 0 ||
                    this.$refs.tableRef.getUpdateRecords().length > 0) {
                    this.$confirm("搜索会丢失本次新增/编辑/删除的数据，确定继续吗?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(() => {
                        this.loading = true;
                        findList(Object.assign(params, this.query)).then(res => {
                            const data = res.data.data;
                            // this.page.total = data.total;
                            this.list = data;
                            this.loading = false;
                            this.selectionClear();
                            this.isEdit = false;
                            this.formateDate(this.list);
                        });
                    })
                } else {
                    this.loading = true;
                    findList(Object.assign(params, this.query)).then(res => {
                        const data = res.data.data;
                        // this.page.total = data.total;
                        this.list = data;
                        this.loading = false;
                        this.selectionClear();
                        this.isEdit = false;
                        this.formateDate(this.list);
                    });
                }
            },

        }
    };
</script>

<style scoped>
    :deep(.vxe-pulldown.size--medium) {
        z-index: 99999 !important;
    }

    .vxe-table--tooltip-wrapper {
        z-index: 10000 !important;
    }

    :deep(.vxe-table--fixed-right-wrapper) {
        z-index: 99999 !important;
    }
</style>
